<?php

/*Task*/

namespace App\Tools;

use App\Tools\Curl;
use App\Tools\FunTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Task {
	private $config;
	private $museFrameConfig;

	public function __construct() {
		//测试
		// $this->config = [
		// 	'apiHost' => 'https://power.girlgenerator.ai/paint/task/api/create',
		// 	'app_secret' => 'dd5c1434a197d96fba6f14b96e9256c6',
		// 	'app_key'=> '44b202f8504fcb6641a459c84e18c225',
		// 	'task_expire' => config('app.task_expire_time'),//task任务过期时间
		// ];
		//正式
		$this->config = [
			'apiHost' => 'https://power.girlgenerator.ai/paint/task/api/create',
			'app_secret' => '1e5d39b129c92a53de1df95014eb497e',
			'app_key'=> '2179aff2dbd3ce24297dc878af8c3741',
			'task_expire' => config('app.task_expire_time'),//task任务过期时间
		];

		$this->museFrameConfig = [
			'apiHost' => 'http://47.236.118.94:7860/museframe/submit/createVideo',
			'apiImageToVideoHost' => 'http://47.236.118.94:7860/museframe/submit/openApi/imageToVideo',
			
		];

	}

	public function checkAddTaskRepeat($deviceId, $userId){
		$repeat = 0;
		$now = date('Y-m-d H:i:s');
		if ($userId > 0) {
			$repeat = DB::table('task_img')->where('user_id',$userId)->where('status',0)->where('expire_time','>=', $now)->count();
		}else{
			$repeat = DB::table('task_img')->where('device_id',$deviceId)->where('status',0)->where('expire_time','>=', $now)->count();
		}

		return $repeat;
	}

	/**
	 * @desc  添加生成图片的任务
	 * @return string
	 * */
	public function addTask($data) {

		$postData = [];
		$postData['task_id'] = $data['task_id'] ?? '';
		$postData['model'] = $data['model'] ?? '';
		$postData['type'] = $data['type'] ?? 1;
		$postData['prompt'] = $data['prompt'] ?? '';
		$postData['negative_prompt'] = $data['negative_prompt'] ?? '';
		$postData['drawing_url'] = $data['drawing_url'] ?? '';
		$postData['width'] = $data['width'] ?? 512;
		$postData['height'] = $data['height'] ?? 768;
		$postData['is_high'] = $data['is_high'] == 1 ? 'y' : 'n';
		$postData['translate'] = 'y';//是否翻译
		$postData['filter_sensitive'] = 'n';//是否过滤敏感词
		$postData['img_validate'] = 'n'; //是否鉴黄
		$data['translate'] = $postData['translate'];
		$data['filter_sensitive'] = $postData['filter_sensitive'];
		$data['img_validate'] = $postData['img_validate'];
		$isVip = $this->userIsVip($data['user_id']);
		$isTry = $isVip == true ? 2 : 1;
		$data['is_try'] = $isTry;

		if (isset($data['special']) && $data['special'] == 1) {//特殊逻辑，不扣点数
			$data['dot'] = 0;
		}else{
			$data['dot'] = $data['is_high'] == 1 ? FunTool::getHighDrawingDot() : 0;
		}

		if (isset($data['is_video']) && $data['is_video'] == 1) {
			$data['dot'] = FunTool::getImageVideoDot();
		}

		if (1 == FunTool::getPlatform() && in_array($postData['type'], [1,2])) {//IOS文生图
			$postData['clothing_adjuster'] = -1;
			$postData['img_validate'] = 'y';
			$postData['filter_sensitive'] = 'y';
		}
		$postData['clothing_adjuster'] = -1;
		$postData['img_validate'] = 'y';
		$postData['filter_sensitive'] = 'y';
		$id = $this->addData($data);//加入task_img任务表

		if ($postData['type'] == 4) {
			$headers = array();
			$headers[] = "Content-Type:application/json";
			$taskId = $data['task_id'];
			$params = [
				'motion' => $data['motion'], 'prompt' => $data['prompt'],
				'proportion' => $data['proportion'], 'videoDuration' => $data['videoDuration'],
				'videoQuantity' => $data['videoQuantity'], 'taskId' => $data['task_id'], 'consumer' => 'dalle_app'
			];

			Log::info('addTask params', [$params]);

			$curl = new Curl();
			$result = $curl->curl_request($this->museFrameConfig['apiHost'], $params, 'json', 'POST', $headers);
		} else {
			$headers = [];
			$headers[] = "KEY:".$this->config['app_key'];
			$curl = new Curl();
			$result = $curl->curl_request($this->config['apiHost'], $postData, 'urlencoded', 'POST', $headers);
			Log::info('addTask postData', [$postData]);
			if (empty($result) || !isset($result['code']) || $result['code']!=200) {
				$result = $curl->curl_request($this->config['apiHost'], $postData, 'urlencoded', 'POST', $headers);
			}

			Log::info('addTask postData', ['postData' => $postData, 'result' => $result]);
		}

		$retData = [
            'status' => 0,
            'url' => '',
            'size' => 1,
            'index' => 1,
            'time' => 8,
            'task_id' => $data['task_id'],
            'refresh_uri' => '/v2/opus/task?task_id=' . $data['task_id'],
            'refresh_time' => 5,
            'prompt' => $data['prompt'],
            'type' => $data['type'],
            'negative_prompt' => $data['negative_prompt'],
            'height' => $data['height'],
            'width' => $data['width'],
            'model_id' => intval($data['model_id']),
            'is_high' => $data['is_high'],
            'prepare_id'=>$data['prepare_id'],
            'is_video' => $data['is_video'] ?? 0
        ];

        if (!empty($task_info['extend'])) {
        	$extend = json_decode($task_info['extend']);
        }else{
        	$extend = [];
        }
        $extend['task_loading'] = $retData;

        DB::table('task_img')->where('id',$id)->update(['revert'=>json_encode($result),'extend'=>json_encode($extend)]);

		return $retData;
	}

	/**
	 * 写入task_img任务表
	 */
	public function addData($data) {	
		$aData = [];
		$aData['task_id'] = $data['task_id'] ?? '';
		$aData['user_id'] = $data['user_id'] ?? 0;
		$aData['model_id'] = $data['model_id'] ?? 0;
		$aData['model'] = $data['model'] ?? '';
		$aData['type'] = $data['type'] ?? 1;
		$aData['prompt'] = $data['prompt'] ?? '';
		$aData['negative_prompt'] = $data['negative_prompt'] ?? '';
		$aData['drawing_url'] = $data['drawing_url'] ?? '';
		$aData['width'] = $data['width'];
		$aData['height'] = $data['height'];
		$aData['is_high'] = $data['is_high'] ?? 0;
		$aData['is_video'] = $data['is_video'] ?? 0;
		$aData['translate'] = $data['translate'] == 'y' ? 1 : 2;
		$aData['filter_sensitive'] = $data['filter_sensitive'] == 'y' ? 1 : 2;
		$aData['img_validate'] = $data['img_validate'] == 'y' ? 1 : 2;
		$aData['style_id'] = $data['style_id'] ?? 0;
		$aData['prepare_id'] = $data['prepare_id'] ?? 0;
		$aData['is_try'] = $data['is_try'];
		$aData['device_id'] = FunTool::getDeviceId();
		$aData['dot'] = $data['dot'];
		$aData['platform'] = FunTool::getPlatform() ?? 0;
		$aData['machine_id'] = $data['machine_id'] ?? '';
		$aData['is_style_orginal'] = $data['is_style_orginal'] ?? 0;
		$aData['created_at'] = FunTool::getCurrentTime();
		$now = strtotime(FunTool::getCurrentTime()) + $this->config['task_expire'];
		$aData['expire_time'] = date('Y-m-d H:i:s', $now);

		$id = DB::table('task_img')->insertGetId($aData);
		
		return $id;
	}

	/**
	 * 作图中心回调接口
	 */
	public function webHooks($data){

		$task_id = $data['task_id'];
		$task_info = DB::table('task_img')->where('task_id',$task_id)->first();
		if (empty($task_info)) {
			return ['code'=>500, 'msg'=>'任务信息为空'];
		}
		$task_info = (array)$task_info;
		$img_url = $data['img_url'] ?? '';
		$img_thumb_url = $data['img_thumb_url'] ?? '';
		$status = $data['status'];
		$is_nsfw = isset($data['is_nsfw']) && $data['is_nsfw'] == 'y' ? 'y' : 'n';
		$isNsfw = $is_nsfw == 'y' ? 1 : 2;
		$prompt_use = $data['prompt_use'] ?? '';
		$validate_status = $data['validate_status'] ?? '';

		$insertData = [];
		$insertData['task_id'] = $task_id;
		$insertData['user_id'] = $task_info['user_id'];
		$insertData['prompt'] = $task_info['prompt'];
		$insertData['prompt_use'] = $prompt_use;
		$insertData['device_id'] = $task_info['device_id'];
		$insertData['url'] = $img_url;
		$insertData['created_at'] = FunTool::getCurrentTime();
		$insertData['title'] = $task_info['prompt'];
		$insertData['width'] = $task_info['width'];
		$insertData['height'] = $task_info['height'];
		$insertData['dot'] = $task_info['dot'];
		$insertData['negative_prompt'] = $task_info['negative_prompt'];
		$insertData['type'] = $task_info['type'];
		$insertData['use_dot'] = $task_info['dot'];
		$insertData['drawing_id'] = $task_info['model_id'];
		$insertData['drawing_image'] = $task_info['drawing_url'];
		$insertData['is_try'] = $task_info['is_try'];
		$insertData['style_id'] = $task_info['style_id'];
		$insertData['is_style_orginal'] = $task_info['is_style_orginal'];
		$insertData['platform'] = $task_info['platform'];
		$insertData['machine_id'] = $task_info['machine_id'];
		$insertData['prepare_id'] = $task_info['prepare_id'];
		//$insertData['thumb_url'] = $img_thumb_url;
		$insertData['is_high'] = $task_info['is_high'];
		//$insertData['nsfw'] = $isNsfw;

		if ('success' == $status) {
			if ($data['validate_status'] == 'fail' ) {//鉴黄不通过
				$new_url = $this->jianHuang($task_info);
				if (!empty($new_url)) {
					$insertData['url'] = $new_url;
				}
			}
			$res = DB::table('opus')->insertGetId($insertData);
			$task_extend = json_decode($task_info['extend'], true);
			$task_extend['success_img_url'] = $img_url;
			$task_extend['success_img_thumb_url'] = $img_thumb_url;
			$task_extend['task_loading']['status'] = 2;//2的时候，端上跳转到结果页
			if ($task_info['is_video'] == 1) {
				$task_extend['task_loading']['status'] = 1;
			}

			$task_extend['task_loading']['url'] = $img_url;
			$task_extend['task_loading']['nsfw']= $isNsfw;
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>1, 
				'webhooks'=>json_encode($data),
				'extend'=>json_encode($task_extend)
			]);

			Log::info('addVideoTask', ['task_info' => $task_info]);

			//处理视频逻辑
			if (isset($task_info['is_video']) && $task_info['is_video']) {
				$headers = array();
				$headers[] = "Content-Type:application/json";
				$params = [
					'motion' => 1, 'prompt' => $task_info['prompt'],
					'proportion' => '16:9', 'videoDuration' => 3,
					'videoQuantity' => 1, 'taskId' => $task_id, 'consumer' => 'https://overseas.dalleai.art/shell/image_video_webhooks',
					'imgUrl' => str_replace("https", "http", $img_url)
				];

				Log::info('addVideoTask', ['params' => $params]);

				$curl = new Curl();
				$result = $curl->curl_request($this->museFrameConfig['apiImageToVideoHost'], $params, 'json', 'POST', $headers);

				Log::info('addVideoTask', ['params' => $params, 'result' => $result]);
			}

		}else{
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>2, 
				'webhooks'=>json_encode($data)
			]);
			if ($task_info['dot'] > 0 && $task_info['user_id']>0) {//制作失败，返回点数
				DB::table('user')->where('id',$task_info['user_id'])->increment('dot',$task_info['dot']);
			}
		}

		return ['code'=>200, 'msg'=>'ok'];

	}

	/**
	 * 鉴黄的逻辑，鉴黄后替换图片
	 */
	public function jianHuang($task_info){

		$img_url = '';
		$file_url = ENV('APP_FILES_URL');

		if (1 == $task_info['platform']) {//苹果的
			if (1 == $task_info['is_try']) {
				$randArr = DB::table('model_style_special')->where('model_id',$task_info['model_id'])->select('id','img')->get();
				$arrMap = [];
				foreach ($randArr as $key => $value) {
					$arrMap[$key] = $value->img;
				}
				$randId = rand(0, count($arrMap)-1);
				$img = $arrMap[$randId] ?? '';
				if ($img) {
					$img_url = $file_url.'/'.$img;
				}else{
					$img_url = $file_url.'/default/default-audit-failure.png';
				}
				
			}else{
				$img_url = $file_url.'/default/default-audit-failure.png';
				if ($task_info['dot'] > 0 && $task_info['user_id'] > 0) {
					DB::table('user')->where('id',$task_info['user_id'])->increment('dot', $task_info['dot']);
				}
			}
		}
		return $img_url;

	}


	public function userIsVip($userId){
		$isvip = false;
		if ($userId) {
			$uinfo = DB::table('user')->where('id',$userId)->first();
			if ($uinfo) {
				if ($uinfo->is_super_vip == 1 || time() < $uinfo->vip_exp) {
					$isvip = true;
				}
			}
		}
		return $isvip;
	}

	public function isPay($userId, $deviceId){
		$week = array_merge(config('app.apple_id_map.vip_arr'), config('app.google_id_map.vip_arr'));
		$life = array_merge(config('app.apple_id_map.life_arr'), config('app.google_id_map.life_arr'));
		$arr = array_merge($week, $life);
		if ($userId > 0) {
			$count = DB::table('pay_order')->where('status',1)->where('user_id',$userId)->whereIn('google_id',$arr)->count();
		}else{
			$count = DB::table('pay_order')->where('status',1)->where('device_id',$deviceId)->whereIn('google_id',$arr)->count();
		}
		return $count;
	}


	/**
	 * 视频生成中心回调接口
	 */
	public function webVedioHooks($data){

		$task_id = $data['task_id'];
		$task_info = DB::table('task_img')->where('task_id',$task_id)->first();
		if (empty($task_info)) {
			return ['code'=>500, 'msg'=>'任务信息为空'];
		}
		$task_info = (array)$task_info;
		$img_url = $data['oss_url'] ?? '';
		$img_thumb_url = $data['oss_url'] ?? '';
		$status = $data['status'];
		$is_nsfw = isset($data['is_nsfw']) && $data['is_nsfw'] == 'y' ? 'y' : 'n';
		$isNsfw = $is_nsfw == 'y' ? 1 : 2;
		$prompt_use = $data['prompt_use'] ?? '';
		$validate_status = $data['status'] ?? '';

		$insertData = [];
		$insertData['task_id'] = $task_id;
		$insertData['user_id'] = $task_info['user_id'];
		$insertData['prompt'] = $task_info['prompt'];
		$insertData['prompt_use'] = $prompt_use;
		$insertData['device_id'] = $task_info['device_id'];
		$insertData['url'] = $img_url;
		$insertData['created_at'] = FunTool::getCurrentTime();
		$insertData['title'] = $task_info['prompt'];
		$insertData['width'] = $task_info['width'];
		$insertData['height'] = $task_info['height'];
		$insertData['dot'] = $task_info['dot'];
		$insertData['negative_prompt'] = $task_info['negative_prompt'];
		$insertData['type'] = $task_info['type'];
		$insertData['use_dot'] = $task_info['dot'];
		$insertData['drawing_id'] = $task_info['model_id'];
		$insertData['drawing_image'] = $task_info['drawing_url'];
		$insertData['is_try'] = $task_info['is_try'];
		$insertData['style_id'] = $task_info['style_id'];
		$insertData['is_style_orginal'] = $task_info['is_style_orginal'];
		$insertData['platform'] = $task_info['platform'];
		$insertData['machine_id'] = $task_info['machine_id'];
		$insertData['prepare_id'] = $task_info['prepare_id'];
		//$insertData['thumb_url'] = $img_thumb_url;
		$insertData['is_high'] = $task_info['is_high'];
		//$insertData['nsfw'] = $isNsfw;

		if ('success' == $status) {
			// if ($data['validate_status'] == 'fail' ) {//鉴黄不通过
			// 	$new_url = $this->jianHuang($task_info);
			// 	if (!empty($new_url)) {
			// 		$insertData['url'] = $new_url;
			// 	}
			// }
			$res = DB::table('opus')->insertGetId($insertData);
			$task_extend = json_decode($task_info['extend'], true);
			$task_extend['success_img_url'] = $img_url;
			$task_extend['success_img_thumb_url'] = $img_thumb_url;
			$task_extend['task_loading']['status'] = 2;//2的时候，端上跳转到结果页
			$task_extend['task_loading']['url'] = $img_url;
			$task_extend['task_loading']['nsfw']= $isNsfw;
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>1, 
				'webhooks'=>json_encode($data),
				'extend'=>json_encode($task_extend)
			]);

		}else{
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>2, 
				'webhooks'=>json_encode($data)
			]);
			if ($task_info['dot'] > 0 && $task_info['user_id']>0) {//制作失败，返回点数
				DB::table('user')->where('id',$task_info['user_id'])->increment('dot',$task_info['dot']);
			}
		}

		return ['code'=>200, 'msg'=>'ok'];

	}



	/**
	 * 视频生成中心回调接口-图生视频
	 */
	public function webImageVedioHooks($data){

		$task_id = $data['task_id'];
		$task_info = DB::table('task_img')->where('task_id',$task_id)->first();
		if (empty($task_info)) {
			return ['code'=>500, 'msg'=>'任务信息为空'];
		}
		$task_info = (array)$task_info;
		$img_url = $data['oss_url'] ?? '';
		$img_thumb_url = $data['oss_url'] ?? '';
		$status = $data['status'];
		$is_nsfw = isset($data['is_nsfw']) && $data['is_nsfw'] == 'y' ? 'y' : 'n';
		$isNsfw = $is_nsfw == 'y' ? 1 : 2;
		$prompt_use = $data['prompt_use'] ?? '';
		$validate_status = $data['status'] ?? '';

	
		if ('success' == $status) {
			// $res = DB::table('opus')->insertGetId($insertData);
			DB::table('opus')->where('task_id',$task_info['task_id'])->update([
				// 'status'=>2, 
				'video_url'=> $img_url
			]);

			$task_extend = json_decode($task_info['extend'], true);
			$task_extend['success_video_url'] = $img_url;
			$task_extend['task_loading']['status'] = 2;
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>1, 
				'extend'=>json_encode($task_extend)
			]);

		}else{
			DB::table('task_img')->where('id',$task_info['id'])->update([
				'status'=>2, 
				'webhooks'=>json_encode($data)
			]);
			if ($task_info['dot'] > 0 && $task_info['user_id']>0) {//制作失败，返回点数
				DB::table('user')->where('id',$task_info['user_id'])->increment('dot',$task_info['dot']);
			}
		}

		return ['code'=>200, 'msg'=>'ok'];

	}



}
